<?php

namespace app\controller;

use app\BaseController;
use app\service\Mq;

class MqDemo extends BaseController {
    //简单模式
    public function pushDemo1() {
        $mq = new Mq();
        for ($i = 0; $i < 10; $i++) {
            $mq->producer(['id' => $i, 'name' => '张三' . $i], 'queueDemo1');
        }
        echo 'success';
    }

    //订阅模式
    public function pushDemo3() {
        $mq = new Mq();
        for ($i = 0; $i < 10; $i++) {
            $mq->producer(['id' => $i, 'name' => '张三' . $i], '', 'phpdemo.fanout', 'fanout');
        }
        echo 'success';
    }

    //路由模式
    public function pushDemo4() {
        $mq = new Mq();
        for ($i = 0; $i < 20; $i++) {
            $routingKey = ($i % 2 == 1) ? 'info' : 'error';
            $mq->producer(['id' => $i, 'name' => '张三' . $i, 'routingKey' => $routingKey], $routingKey, 'phpdemo.direct', 'direct');
        }
        echo 'success';
    }

    //主题模式
    public function pushDemo5() {
        $mq = new Mq();
        $a = ['a', 'b', 'c'];
        foreach ($a as $val) {
            for ($i = 0; $i < 20; $i++) {
                $routingKey = $val . '.';
                $routingKey .= ($i % 2 == 1) ? 'info' : 'error';
                $mq->producer(['id' => $i, 'name' => '张三' . $i, 'routingKey' => $routingKey], $routingKey, 'phpdemo.topic', 'topic');
            }
        }
        echo 'success';
    }

    //在上面主题模式的基础上,改造成一个死信队列,可以实现延时消费功能(过期时间+死信队列来实现)
    public function pushDemo6() {
        $mq = new Mq();
        for ($i = 0; $i < 20; $i++) {
            $routingKey = ($i % 2 == 1) ? 'info' : 'error';
            $ttl = ($i % 2 == 1) ? 3000 : 8000; //定义过期时间,info存活时间3秒,否则8秒
            $dlx = [
                'exchange' => 'phpdemo.dlx.exchange',
                'ttl' => $ttl,
                'routingKey' => $routingKey
            ];

            //不同存活时间的消息不能放到同一个队列中,因此下面区分出两个队列名 'phpdemo.queue.normal.' . $routingKey
            $mq->producer(['id' => $i, 'name' => '张三' . $i, 'routingKey' => $routingKey], 'phpdemo.queue.normal.' . $routingKey, '', false, true, $dlx);
        }
        echo 'success';
    }
}